package com.blobfish.producter;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Console;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.blobfish.kit.FileKit;
import com.blobfish.kit.TranslatedCacheUtil;

import java.io.File;
import java.util.*;

/**
 * 获取待翻译的内容，更新到map中
 * @author huangbo
 */
public class GetToBeTranslated {

    public static void main(String[] args) {
        List<File> fileList = FileKit.listAllFile();
        Set<String> resultSet = new HashSet<>(1300);
        for (File file:
                fileList) {
            String langValueStr = cn.hutool.core.io.FileUtil.readUtf8String(file);
            langValueStr = langValueStr.substring(15);
            langValueStr = langValueStr.replaceAll("(?<!:)\\/\\/.*|\\/\\*(\\s|.)*?\\*\\/", "");
            try {
                JSONObject obj = JSONUtil.parseObj(langValueStr);
                translate(obj, resultSet);
            } catch (Exception e) {
                Console.error("json文件不标准:{},错误信息为:{}", FileUtil.getAbsolutePath(file), e.getMessage());
            }
        }

        Iterator<String> it = resultSet.iterator();
        while (it.hasNext()) {
            String str = it.next();
            TranslatedCacheUtil.addChineseStr(str);
        }
    }

    public static void translate(Object obj, Set<String> chinessSet) {
        if (obj instanceof JSONObject) {
            final JSONObject tmpObj = (JSONObject) obj;
            for (final String key : tmpObj.keySet()) {
                if (tmpObj.get(key) instanceof String) {
                    String resultStr = tmpObj.get(key).toString();
                    if (StrUtil.isNotBlank(resultStr)) {
                        chinessSet.add(resultStr);
                    }
                } else {
                    translate(tmpObj.get(key), chinessSet);
                }
            }
        } else if (obj instanceof JSONArray) {
            JSONArray tmpArray = (JSONArray) obj;
            for (Object item : tmpArray) {
                translate(item, chinessSet);
            }
        }
    }
}
